package gugu.services.impl;

import java.util.List;

import javax.annotation.Resource;

import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import gugu.domain.Question;
import gugu.domain.Survey;
import gugu.domain.SurveyTypeEnum;
import gugu.domain.User;
import gugu.services.SurveyService;

@Component("surveyService")
public class SurveyServiceImpl implements SurveyService{
	
	@Resource
	private MongoOperations mongoOpts;
	
	@Override
	public void createSurvey(Survey survey) {
		mongoOpts.insert(survey);
	}

	@Override
	public void disableSurvey(Survey survey) {
		survey.setType(SurveyTypeEnum.OFFLINE);
		mongoOpts.save(survey);
	}

	@Override
	public void updateSurvey(Survey survey) {
		mongoOpts.save(survey);
	}

	@Override
	public Survey findSurvey(String id) {
		return mongoOpts.findById(id, Survey.class);
	}

	@Override
	public List<Survey> findSurvey(User owner) {
		return mongoOpts.find(
				new Query(Criteria.where("owner.$id").is(
						new ObjectId(owner.getId()))), Survey.class);
	}

	@Override
	public void addSurveyQuestion(Survey survey, Question... question) {
		for(Question que:question){
			que.setSurvey(survey);
			mongoOpts.save(que);
		}
	}

	@Override
	public void removeSurveyQuestion(Survey survey, Question... question) {
		for(Question que:question){
			if(!survey.getId().equals(que.getSurvey().getId())){
				throw new IllegalArgumentException("The survey instance associated with the question is not applicable with the given parameter survey:"+survey+" question.getsurvey"+que.getSurvey());
			}
			que.setSurvey(survey);
			mongoOpts.remove(que);
		}
	}

	@Override
	public void removeSurveyQuestion(Survey survey) {
		mongoOpts.remove(new Query(Criteria.where("survey.$id").is(new ObjectId(survey.getId()))), Question.class);
	}

	@Override
	public List<Question> findQuestions(Survey survey) {
		return mongoOpts.find(new Query(Criteria.where("survey.$id").is(new ObjectId(survey.getId()))), Question.class);
	}

}
